<template>
  <el-card shadow="hover">
    <p>第一张默认为商品主图片</p>
    <el-upload
      class="upload-demo"
      ref="upload"
      action="http://localhost:51154/api/Images"
      :auto-upload="false"
      list-type="picture-card"
      :on-success="handleSuccess"
      :on-error="handleError"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    </el-upload>
  </el-card>
</template>

<script>
export default {
  props:["selectImages","successEvent"],
  methods: {
    // 启动上传
    submitUpload() {
      if(this.$refs.upload.uploadFiles==0){
        this.$message({
          message:"你没有选择一张商品图片",
          type:"warning"
        })
      }
      this.$refs.upload.submit();
    },

    // 上传成功回调
    handleSuccess(res, file) {
      // 将图片路径传给spu
      this.selectImages(res.data[0]);

      // 判断图片是否全部上传成功
      let files = this.$refs.upload.uploadFiles.filter(
        (item) => item.status !== "success"
      );
      if (files.length == 0) {
        this.$message({
          message: `上传完成`,
          type: "success",
        });

        // 图片上传成功后调用回调
        this.successEvent();
      }
    },

    // 失败回调
    handleError(err,file){
      this.$message({
        message:`${file.name}上传失败,${err}`,
        type:"warning"
      })
    }
  },
};
</script>

<style scoped>
.el-card {
}
</style>